<template>
  <div class="content">
    <h3>欢迎来到LSB的博客</h3>
    <div class="block">
      <el-avatar :size="50" :src="user.avatar"></el-avatar>
      <div>{{ user.username }}</div>
      <div class="action">
        <span><el-link href="/blogs">主页</el-link></span>
        <el-divider direction="vertical"></el-divider>
        <span><el-link type="success" @click="toBlogEdit">发表文章</el-link></span>

        <el-divider direction="vertical"></el-divider>
        <span v-if="!hasLogin"><el-link type="primary" @click="toLogin">登录</el-link></span>
        <span v-else><el-link type="danger" @click="logout">退出</el-link></span>

      </div>
    </div>
  </div>
</template>

<script>
    export default {
      name: "Header",
      data () {
        return {
          user: {
            username: '请先登录',
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
          },
          hasLogin: false
        }
      },
      methods: {
          logout() {
            this.$axios.get("/logout", {
              headers: {
                "Authorization": localStorage.getItem("token")
              }
            }).then(result => {
              this.$store.commit('REMOVE_INFO');
              this.$router.push('/login');
            })
          },
          toLogin() {
            this.$router.push("/login");
          },
          toBlogEdit() {
            this.$router.push('/blog/add');
          }
      },
      created() {
        if(this.$store.getters.getUser.username){
          this.user.username = this.$store.getters.getUser.username;
          this.user.avatar = this.$store.getters.getUser.avatar;

          this.hasLogin = true;
        }
      }
    }
</script>

<style scoped>
  .content {
    max-width: 900px;
    margin: 0 auto;
    text-align: center;
  }

  .action {
    margin: 10px 0;
  }
</style>
